﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using System.Xml.Serialization;

namespace WebLib.AuthorizeService
{
    public class AuthenticationModule : IHttpModule
    {
        private HttpApplication _app;

        private void OnAuthenticate(object sender, EventArgs e)
        {
            _app = (HttpApplication)sender;
            var req = _app.Request;
            var res = _app.Response;

            if (req.Cookies.Count > 0 && req.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                var cookie = req.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    var str = cookie.Value;

                    var userIdentity = GetUserData(str);
                    //var principal = new Principal(userIdentity, userIdentity.UserRoles);
                    var principal = new GenericPrincipal(userIdentity, userIdentity.UserRoles);
                    _app.Context.User = principal;
                    Thread.CurrentPrincipal = principal;
                }
            }
        }

        private Identity GetUserData(string str)
        {
            var ticket = FormsAuthentication.Decrypt(str);
            var xs = new XmlSerializer(typeof(Identity));
            if (ticket != null)
            {
                var sr = new StringReader(ticket.UserData);
                return (Identity)xs.Deserialize(sr);
            }

            return null;
        }


        #region IHttpModule 멤버

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            _app = context;
            _app.AuthenticateRequest += OnAuthenticate;
        }

        #endregion
    }
}
